import configparser
import math
import random
import threading
import time
from sqlalchemy import Column, String, create_engine, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import requests


headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36",
    "cookie": ""
}
sleep_time = 3


# 创建对象的基类:
Base = declarative_base()
# 定义User对象:
class video_list(Base):
    # 表的名字:
    __tablename__ = 'video_list'

    # 表的结构:
    bvid = Column(String(20), primary_key=True)
    typeid = Column(Integer)
    author = Column(String(20))
    mid = Column(Integer)
    created = Column(Integer)
    length = Column(String(20))
    title = Column(String(100))
    is_union_video = Column(Integer)

class video_d(Base):
    # 表的名字:
    __tablename__ = 'video_d'

    # 表的结构:
    bvid = Column(String(20), primary_key=True)
    down_time = Column(Integer)
    state = Column(Integer)
    reply = Column(Integer)
    view = Column(Integer)
    danmaku = Column(Integer)
    favorite = Column(Integer)
    coin = Column(Integer)
    share = Column(Integer)
    now_rank = Column(Integer)
    his_rank = Column(Integer)
    evaluation = Column(Integer)

def bvid_list():
    bv_list = []
    engine = create_engine("mysql+pymysql://root:Aa380562113.@192.168.2.8:3306/bilibili?charset=utf8")
    DBSession = sessionmaker(bind=engine)
    session = DBSession()
    # 创建Query查询，filter是where条件，最后调用one()返回唯一行，如果调用all()则返回所有行:
    bv = session.query(video_list).filter().all()
    for i in bv:
        bv_list.append(i.bvid)
    session.close()
    return bv_list



def config():
    ck = []
    cp = configparser.RawConfigParser()
    cp.read('config.ini')
    # ck.append(cp.get('bilibili', 'cookie1'))
    # ck.append(cp.get('bilibili', 'cookie2'))
    ck.append(cp.get('bilibili', 'cookie3'))
    # up_list = cp.get('up_list', 'up_list')
    return ck


def up_get(cookie):
    url1 = "http://api.bilibili.com/x/space/acc/info?mid={}"
    url2 = "http://api.bilibili.com/x/web-interface/card?mid={}"
    url3 = "http://api.bilibili.com/x/space/upstat?mid={}"
    headers['cookie'] = cookie
    # for i in up_list:
    x = 0
    while x <= 1000 and x > -1:
        i = random.randint(0, 1100000000)
        res1 = requests.get(url1.format(i), headers=headers)
        res1 = res1.json()
        if res1.get("message") == '请求被拦截':
            x = -1
            print("请求被拦截")
        elif res1.get("message") == "0":
            up_data1 = {
                "mid": res1.get("data").get("mid"),
                "name": res1.get("data").get("name"),
                "sex": res1.get("data").get("sex"),
                "level": res1.get("data").get("level"),
                "silence": res1.get("data").get("silence"),
                "birthday": res1.get("data").get("birthday"),
                "official": res1.get("data").get("official").get("role"),
                "vip": res1.get("data").get("vip").get("type"),
            }
            if up_data1.get('silence') == 1:
                print("封禁中", up_data1)
                x += 1
                time.sleep(sleep_time)
            elif up_data1.get('level') == 0:
                print("0级号", up_data1)
                x += 1
                time.sleep(sleep_time)
            else:
                res2 = requests.get(url2.format(i), headers=headers)
                res2 = res2.json()
                if res2.get("message") == '请求被拦截':
                    x = -1
                    print("请求被拦截")
                else:
                    up_data2 = {
                        "mid": res2.get("data").get("card").get("mid"),
                        "fans": res2.get("data").get("card").get("fans"),
                        "friend": res2.get("data").get("card").get("friend"),
                        "archive_count": res2.get("data").get("archive_count"),
                    }
                    if up_data2.get("archive_count") > 0:
                        res3 = requests.get(url3.format(i), headers=headers)
                        res3 = res3.json()
                        if res3.get("message") == '请求被拦截':
                            x = -1
                            print("请求被拦截")
                        else:
                            up_data3 = {
                                "archive": res3.get("data").get("archive").get("view"),
                                "article": res3.get("data").get("article").get("view"),
                                "likes": res3.get("data").get("likes"),
                            }
                            print("UP主", dict(dict(up_data1, **up_data2), **up_data3))
                            x += 1
                            time.sleep(sleep_time)
                    else:
                        print("普通用户", dict(up_data1, **up_data2))
                        x += 1
                        time.sleep(sleep_time)
        else:
            print(i, res1)
            x += 1
            time.sleep(sleep_time)




def get_video_d(cookie, i, s):
    url = "http://api.bilibili.com/x/space/arc/search?mid={}&pn={}&ps=30"
    headers['cookie'] = cookie
    res = requests.get(url.format(i, s), headers=headers)
    res = res.json()
    bv_list=bvid_list()
    if res.get("code") == 0:
        for x in res.get("data").get("list").get("vlist"):
            if x.get("bvid") not in bv_list:
                session = DBSession()
                new_video = video_list(bvid=x.get("bvid"),
                                       typeid=x.get("typeid"),
                                       author=x.get("author"),
                                       mid=x.get("mid"),
                                       created=x.get("created"),
                                       length=x.get("length"),
                                       title=x.get("title"),
                                       is_union_video=x.get("is_union_video"))
                session.add(new_video)
                session.commit()
                session.close()

            # url2 = "http://api.bilibili.com/x/web-interface/view?bvid={}"
            # res2 = requests.get(url2.format(data.get("bvid")), headers=headers)
            # res2 = res2.json()
            # if res2.get("code") == 0:
            #     data2 = {
            #         "爬取时间": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time())),
            #         "视频状态": res2.get("data").get("state"),
            #         "评论数": res2.get("data").get("stat").get("reply"),
            #         "播放数": res2.get("data").get("stat").get("view"),
            #         "弹幕数": res2.get("data").get("stat").get("danmaku"),
            #         "收藏": res2.get("data").get("stat").get("favorite"),
            #         "投币": res2.get("data").get("stat").get("coin"),
            #         "分享数": res2.get("data").get("stat").get("share"),
            #         "当前排名": res2.get("data").get("stat").get("now_rank"),
            #         "最高排名": res2.get("data").get("stat").get("his_rank"),
            #         "评分": res2.get("data").get("stat").get("evaluation"),
            #     }
            #     print(dict(data, **data2))
            #     time.sleep(5)
            # else:
            #     print(res2.get("message"))
            #     print(data)
            #     return -1
        time.sleep(5)
        return res.get("data").get("page").get("count")
    else:
        print(res.get("message"))
        return -1


def git_video(cookie, id):
    cou = get_video_d(cookie, id, 1)
    if cou > 0 and cou <= 30:
        pass
    elif cou > 30:
        for i in range(2, math.ceil(cou / 30) + 1):
            get_video_d(cookie, id, i)


if __name__ == '__main__':
    pass
    # cookie = config()
    # for i in cookie:
    #     ding1 = threading.Thread(target=git_video, args=(i, 903059))
    #     ding1.start()
    #     time.sleep(0.5)

